import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2')

import urllib
import datetime
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api.urlfetch import fetch
from google.appengine.ext.db import polymodel

class Tunnel(db.Model):
	id = db.StringProperty()

class Message(db.Model):
	time_limit = datetime.timedelta(seconds=10)
	time_cutoff = db.DateTimeProperty(auto_now_add=False)
	message_datetime = db.DateTimeProperty(auto_now_add=True)
	image = db.BlobProperty()
	text = db.StringProperty()
	tunnel = db.ReferenceProperty(Tunnel,
                                   collection_name='messages')

class PostMessage(webapp.RequestHandler):
	def post(self):
		message = Message()	
		message.text = self.request.get('message_text')
		message.time_cutoff = datetime.datetime.now() + Message.time_limit
		message.put()
		self.redirect('/')
								   
class MainPage(webapp.RequestHandler):
	def get(self):
		messages = Message.all().order('-message_datetime')
		now = datetime.datetime.now()
		template_values = {'messages':messages,
						   'now':now}
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication([('/post', PostMessage),
									  ('/', MainPage)
									 ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()